(function(){
  'use strict';

  angular
    .module('client')
    .service('AuthService', AuthService);

  AuthService.$inject = ['$window', '$cookies', '$location', 'indexService', 'TEST_PLUS_AUTH'];
  function AuthService($window, $cookies, $location, indexService, TEST_PLUS_AUTH) {
    this.parseJwt = parseJwt;
    this.saveToken = saveToken;
    this.getToken = getToken;
    this.isAuthenticated = isAuthenticated;
    this.logout = logout;

    function parseJwt(token) {
      var base64Url = token.split('.')[1];
      var base64 = base64Url.replace('-', '+').replace('_', '/');
      return JSON.parse($window.atob(base64));
    }

    function saveToken(token) {
      indexService.setToken(token);
    }

    function getToken() {
      return indexService.getToken();
    }

    function isAuthenticated() {
      var token = this.getToken();
      if (!token && $cookies.get('testplus_auth')) {
        token = $cookies.getObject('testplus_auth').token;
        saveToken(token);
      }
      if (token) {
        var params = this.parseJwt(token);
        return Math.round(new Date().getTime() / 1000) <= params.exp;
      }
      return false;
    }

    function logout() {
      indexService.clearAll();
      var domain = $location.host().substring($location.host().indexOf('.'), $location.host().length);
      if ($cookies.get('testplus_auth')) {
        $cookies.remove("testplus_auth", {domain: domain});
        $cookies.remove("testplus_auth_user", {domain: domain});
        $cookies.remove("testplus_auth");
        $cookies.remove("testplus_auth_user");
      }
      if (-1 !== TEST_PLUS_AUTH.remoteCN.indexOf(domain)) {
        $window.top.location = TEST_PLUS_AUTH.CN;
      } else if (-1 !== TEST_PLUS_AUTH.remoteEN.indexOf(domain)) {
        $window.top.location = TEST_PLUS_AUTH.EN;
      } else {
        $window.top.location = '/';
      }
    }
  }

}());
